package com.baiytfp.hf.HFDataExchange.action.controller.service;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baiytfp.hf.HFDataExchange.action.service.DeptService;
import com.baiytfp.hf.HFDataExchange.action.service.PositionService;
import com.baiytfp.hf.HFDataExchange.action.service.RoleService;
import com.baiytfp.hf.HFDataExchange.common.model.state.RightBelongType;
import com.baiytfp.hf.HFDataExchange.common.model.state.TreeType;
import com.baiytfp.hf.HFDataExchange.common.model.table.User_dept;
import com.baiytfp.hf.HFDataExchange.common.model.table.User_position;
import com.baiytfp.hf.HFDataExchange.common.model.table.User_role;
import com.baiytfp.hf.HFDataExchange.common.utils.CommonUtils;
import com.baiytfp.hf.baiytfp.hfutils.HFCache;
import com.google.gson.JsonArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baiytfp.hf.HFDataExchange.action.service.AuthService;
import com.baiytfp.hf.HFDataExchange.common.utils.CommonUtil;
import com.baiytfp.hf.baiytfp.framework.base.BaseController;
import com.baiytfp.hf.baiytfp.hfutils.HFRequest;
import com.baiytfp.hf.baiytfp.hfutils.HFResponse;


@Controller
@RequestMapping("/service/auth")
public class AuthSController extends BaseController {

	@Autowired
	private AuthService authService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private PositionService positionService;

	
	/*@RequestMapping("tree")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		String  treeType = HFRequest.getIstance().getString(request,"treeType");
		String  objType = HFRequest.getIstance().getString(request,"objType");
		String  objCode = HFRequest.getIstance().getString(request,"objCode");
		if(CommonUtil.isEmpty(treeType) || CommonUtil.isEmpty(objType) || CommonUtil.isEmpty(objCode)) {
			HFResponse.getIstance().returnResult(response, -1, "参数有误",null);
		}else {
			HFResponse.getIstance().returnResult(response, 0, "获取数据成功", authService.trees(treeType,objType, objCode));;
		}
		return null;
	}*/
	private void getTree(HttpServletRequest request, HttpServletResponse response, TreeType treeType) throws Exception {
		String objType = HFRequest.getIstance().getString(request, "type");
		String objCode = HFRequest.getIstance().getString(request, "id");
		if(CommonUtil.isEmpty(objType) || CommonUtil.isEmpty(objCode)) {
			HFResponse.getIstance().returnResult(response, -1, "参数有误",null);
		}else {
			HFResponse.getIstance().returnResult(response, 0, "获取数据成功", authService.trees(treeType.getKey()+"" ,objType, objCode));;
		}
	}

	@RequestMapping("menutree")
	public void menu(HttpServletRequest request,HttpServletResponse response) throws Exception {
		getTree(request, response, TreeType.MANAGE_MENU);
	}

	@RequestMapping("functree")
	public void func(HttpServletRequest request,HttpServletResponse response) throws Exception {
		getTree(request, response, TreeType.MANAGE_FUNC);
	}

	@RequestMapping("authsave")
	public ModelAndView authsave(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map map = converParams(request);
		boolean rs = authService.save((List<Map>) map.get("add"), (List<Map>) map.get("update"));
		if(rs) {
			HFResponse.getIstance().returnResult(response, 0, "保存成功",null);
		}else {
			HFResponse.getIstance().returnResult(response, -1, "保存失败",null);
		}
		return null;
	}

//	@RequestMapping("save")
//	public ModelAndView menuAuthSave(HttpServletRequest request,HttpServletResponse response) throws Exception {
//		JSONObject param = CommonUtil.paseJson(request);
//		List<Map> news = param.getJSONArray("news") != null ? param.getJSONArray("news").toJavaList(Map.class) : null;
//		List<Map> edits = param.getJSONArray("edits") != null ? param.getJSONArray("edits").toJavaList(Map.class) : null;
//		boolean rs = authService.save(news,edits);
//		if(rs) {
//			HFResponse.getIstance().returnResult(response, 0, "保存成功",null);
//		}else {
//			HFResponse.getIstance().returnResult(response, -1, "保存失败",null);
//		}
//		return null;
//	}
	private  Map converParams(HttpServletRequest request) throws Exception {

		JSONObject param = CommonUtils.paseJson(request);

		//System.out.println(param.toJSONString());

		String objCode = param.getString("id");
		String objType = param.getString("type");

		//清除该类型的缓存
		if(objType.equals(RightBelongType.ROLE.getVal()+"")){//对象类型为角色
			//获取该角色的所有用户
			List<User_role> list = roleService.getHasUserCodeByUserRole(objCode);
			for(User_role roleVO : list){
				//清除该用户的菜单权限缓存
				List<Map> rs = (List<Map>) HFCache.getIstance().get(roleVO.getUser_code()+"_menu");
				if(!CommonUtils.isEmpty(rs)){
					HFCache.getIstance().delete(roleVO.getUser_code()+"_menu");
				}
				//清除该用户的功能权限缓存
				rs = (List<Map>) HFCache.getIstance().get(roleVO.getUser_code()+"_func");
				if(!CommonUtils.isEmpty(rs)){
					HFCache.getIstance().delete(roleVO.getUser_code()+"_func");
				}
			}
		}else if(objType.equals(RightBelongType.EMP.getVal()+"")){
			//清除该用户的菜单权限缓存
			List<Map> rs = (List<Map>) HFCache.getIstance().get(objCode+"_menu");
			if(!CommonUtils.isEmpty(rs)){
				HFCache.getIstance().delete(objCode+"_menu");
			}
			//清除该用户的功能权限缓存
			rs = (List<Map>) HFCache.getIstance().get(objCode+"_func");
			if(!CommonUtils.isEmpty(rs)){
				HFCache.getIstance().delete(objCode+"_func");
			}
		}else if(objType.equals(RightBelongType.DEPT.getVal()+"")){
			List<User_dept> list = deptService.getHasUserCodeByUserDept(objCode);
			for (User_dept deptVO : list) {
				//清除该用户的菜单权限缓存
				List<Map> rs = (List<Map>) HFCache.getIstance().get(deptVO.getUser_code()+"_menu");
				if(!CommonUtils.isEmpty(rs)){
					HFCache.getIstance().delete(deptVO.getUser_code()+"_menu");
				}
				//清除该用户的功能权限缓存
				rs = (List<Map>) HFCache.getIstance().get(deptVO.getUser_code()+"_func");
				if(!CommonUtils.isEmpty(rs)){
					HFCache.getIstance().delete(deptVO.getUser_code()+"_func");
				}
			}
		}else if(objType.equals(RightBelongType.POSI.getVal()+"")){
			List<User_position> list = positionService.getHasUserCodeByUserPosi(objCode);
			for (User_position posiVO : list) {
				//清除该用户的菜单权限缓存
				List<Map> rs = (List<Map>) HFCache.getIstance().get(posiVO.getUser_code()+"_menu");
				if(!CommonUtils.isEmpty(rs)){
					HFCache.getIstance().delete(posiVO.getUser_code()+"_menu");
				}
				//清除该用户的功能权限缓存
				rs = (List<Map>) HFCache.getIstance().get(posiVO.getUser_code()+"_func");
				if(!CommonUtils.isEmpty(rs)){
					HFCache.getIstance().delete(posiVO.getUser_code()+"_func");
				}
			}
		}

		Iterator jsonMenu = param.getJSONArray("menu") != null ? param.getJSONArray("menu").iterator() : new JsonArray().iterator();
		Iterator jsonFunc = param.getJSONArray("func") != null ? param.getJSONArray("func").iterator() : new JsonArray().iterator();

		List<Map> add = new ArrayList<>();
		List<Map> update = new ArrayList<>();
		JSONObject tmp = null;
		while(jsonMenu.hasNext()) {
			tmp = (JSONObject) jsonMenu.next();
			tmp.put("obj_code", objCode);
			tmp.put("obj_type", objType);
			tmp.put("tree_type", TreeType.MANAGE_MENU.getKey());

			if("0".equalsIgnoreCase(tmp.getString("edit"))) {
				add.add(tmp.toJavaObject(Map.class));
			}else {
				update.add(tmp.toJavaObject(Map.class));
			}
		}

		while(jsonFunc.hasNext()) {
			tmp = (JSONObject) jsonFunc.next();
			tmp.put("obj_code", objCode);
			tmp.put("obj_type", objType);//对象类型： 1角色 2用户
			tmp.put("tree_type", TreeType.MANAGE_FUNC.getKey());//功能类型 1菜单 2功能
			//tmp.put("id", tmp.getString("edit"));
			if("0".equalsIgnoreCase(tmp.getString("edit"))) {
				add.add(tmp.toJavaObject(Map.class));
			}else {
				update.add(tmp.toJavaObject(Map.class));
			}
		}

		Map rs = new HashMap<>(16);
		rs.put("add", add);
		rs.put("update", update);
		return rs;
	}
}
